const splitStr = '-sPeciAlSpLiT-'
const departmentSet = {}

function createCustomerCompany(dataList, companyId, dbDataList) {
    let nameList = dataList.filter(i => !i.department).map(i => i.部门全称)
    const result = []
    for (const name of nameList) {
        if (!name.includes('\\')) {
            const data = getAddData(dbDataList, companyId, name, 1, null, [])
            if (!data) {
                continue
            }
            result.push(data)
            continue
        }
        const nameSplit = name.split('\\')
        const path = nameSplit.map((name, index) => (dbDataList.find(item => item.name === name && item.level === (index + 1)) || {}).id)
        for (let i = 0; i < nameSplit.length; i++) {
            const data = getAddData(dbDataList, companyId, nameSplit[i], i + 1, path[i - 1], path.slice(0, i))
            if (!data) {
                continue
            }
            result.push(data)
            path[i] = data.id
            dbDataList.push(data)
        }
    }
    return result
}

function getAddData(dbDataList, companyId, name, level, parentId, path) {
    const hasDbData = dbDataList.some(item => item.name === name && item.level === level)
    if (hasDbData) {
        return
    }

    const setKey = name + splitStr + level
    if (departmentSet[setKey]) {
        return
    }
    departmentSet[setKey] = true

    return {
        companyId: companyId,
        name: name,
        level: level,
        path: [...path],
        id: Math.random().toString().slice(2),
        parentId: parentId
    }
}

function setDataDepartmentName(dataList, dbDataList) {
    for (const item of dataList) {
        if (item.部门全称.includes('\\')) {
            const departmentSplit = item.部门全称.split('\\')
            item._db部门层级 = departmentSplit.length
            item._db部门名称 = departmentSplit.pop()
        } else {
            item._db部门层级 = 1
            item._db部门名称 = item.部门全称
        }

        let dbData = dbDataList.find(sub => sub.name === item._db部门名称 && sub.level === item._db部门层级)
        if (dbData) {
            item.department = dbData.数据ID
        }
    }
    return dataList
}

return {
    result: createCustomerCompany(dataList, companyId, dbDataList),
    dataList: setDataDepartmentName(dataList, dbDataList)
}